/**
  * Created by lixiaodi on 2018/10/10.
 */
mini.parse();
var form = new mini.Form("form1");
var toUserInput = mini.get('userId');
var grid=mini.get("datagrid1");
//初始化
$(function(){
    $.ajax({
        url: ajaxUrl + "/user/list.do",
        type: 'POST',
        contentType : "application/json",
        success: function (data) {
            console.log(data);
            var userObj = data.data;
            grid.setData(userObj);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //alert(jqXHR.responseText);
            //CloseWindow();
            console.log('请求失败');
        }
    })
});
//增加(保存)
function SaveData() {
    form.validate();
    if (form.isValid() == false) return;
    var rows=grid.getSelecteds();
    console.log(rows);
    var userIdarr=[];
    rows.forEach(function (item) {
        userIdarr.push(item.userId)
    })
    console.log(userIdarr);

    // rows=JSON.stringify(rows);
    // console.log(rows);
    var ids = form.getData();
    console.log(ids);
    var role = {
        roleId : ids.roleId,
        roleName : ids.roleName,
        roleCode: ids.roleCode,
        roleDescribe : ids.roleDescribe,
        userId:userIdarr
    };
    console.log(role);
    role = JSON.stringify(role);
    $.ajax({
        url: ajaxUrl + "/role/insertRole.do",
        type: 'POST',
        data: role,
        contentType : "application/json",
        success: function (data) {
            CloseWindow("save");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //alert(jqXHR.responseText);
            CloseWindow();
        }
    });
}
//编辑
function SetData(data) {
    if (data.action == "edit") {
        //跨页面传递的数据对象，克隆后才可以安全使用
        data = mini.clone(data);

        $.ajax({
            url: ajaxUrl + "/role/findByRoleId.do?roleId=" + data.id,
            type: 'POST',
            success: function (data) {
                console.log(data);
                data1=mini.clone(data.data);
                console.log(data1.roleId);
                var o = mini.decode(data);
                form.setData(o.data);
                form.setChanged(false);
                $.ajax({
                    url: ajaxUrl + "/role/findByRole.do?roleId=" + data1.roleId,
                    type: 'POST',
                    dataType:'text',
                    success: function (data) {
                        console.log(data);
                        data2=JSON.parse(data);
                        console.log(data2);
                        //获取需要勾选的行
                        var rowsArr = [];
                        data2.forEach(function (item) {
                            var row = grid.findRow(function (row) {
                                if(row.userId == item.userId)
                                    return true;
                            });
                            rowsArr.push(row);
                        });
                        console.log(rowsArr);
                        grid.selects(rowsArr,true);

                        // var dataArr = grid.getData();
                        // console.log(dataArr);
                        // data2.forEach(function (user) {
                        //
                        //     dataArr.forEach(function (item) {
                        //         for(var i=0;i<dataArr.length;i++){
                        //             if(item.userId == user.userId){
                        //                 grid.select(data2[i],true)
                        //             }
                        //         }
                        //
                        //     })
                        // })
                        //
                        // // grid.setData(data2);

                    },
                    error:function(data){
                        mini.alert('失败了');
                    }
                });
            },
            error:function(data){
                mini.alert('失败');
            }
        });

    }else if(data.action == "new"){
        console.log('new');
    }



}
//分配用户
function changePar(e){
	//var btnEdit = this;
	mini.open({
        url: bootPATH + "../frame/frame1/pages/alertBox/toUser.html",
        title: "选择父级菜单",
        width: 500,
        height: 360,
        ondestroy: function (action) {
            //if (action == "close") return false;
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.GetData();
                data = mini.clone(data);    //必须
                var ids = [];
                var names = [];
                for (var i = 0, l = data.length; i < l; i++) {
                    var r = data[i];
                    ids.push(r.userId);
                    names.push(r.userName);
                }
                var id = ids.join(',');
                var nameStr = names.join(',');
                if (data) {
                	toUserInput.setValue(id);
                	toUserInput.setText(nameStr);
                }
            }
        }
    });
}
//父页面获得子页面数据
function GetData() {
    var o = form.getData();
    return o;
}
//关闭页面
function CloseWindow(action) {
    if (action == "close" && form.isChanged()) {
        if (confirm("数据被修改了，是否先保存？")) {
            return false;
        }
    }
    if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action);
    else window.close();
}
function onOk(e) {
    SaveData();
}
function onCancel(e) {
    CloseWindow("cancel");
}
//////////////////////////////////
function onUserChanged(e) {
    var roleId = mini.getbyName("roleId");
    var roleIdValue = roleId.getValue();
    var roles = roleId.text;
    console.log(roleIdValue);
}

//重置
function onReset(){
    var ids = form.getData();
    var userId = ids.userId
    $.ajax({
        url: ajaxUrl + "/user/replacePassword.do?userId=" + userId,
        type:"post",
        success: function (data) {
            console.log(data)
        }
    });

}
//校验编码是否重复
function findByRoleCode(){
	var ids = form.getData();
	var roleCode = ids.roleCode;
	$.ajax({
		type 	: 'POST',
		url  	: ajaxUrl + '/role/findRoleCode.do',
		data 	: {
			roleCode : roleCode
		},
		success : function(data){
			if(data.state == 'error'){
				mini.alert(data.message);
				mini.get('roleCode').setValue(''); 
			}
		},
		error   : function(message) {
			mini.alert(message);
		}
	})
}
//校验名称是否重复
function findByRoleName(){
	var ids = form.getData();
	var roleName = ids.roleName;
	
	$.ajax({
		type 	: 'POST',
		url  	: ajaxUrl + '/role/findRoleName.do',
		data 	: {
			roleName : roleName
		},
		success : function(data){
			if(data.state == 'error'){
				mini.alert(data.message);
				mini.get('roleName').setValue(''); 
			}
		},
		error   : function(message) {
			mini.alert(message);
		}
	})
}
//非空校验
function onNotSpaceValidation(e) {
    if (e.isValid) {
        if (!e.value) {
            e.errorText = "不能为空";
            e.isValid = false;
        }
    }
}
//用户姓名查询
function userInquire() {
    var searchKey = mini.get("searchKey").getValue();
    console.log(searchKey);
   $.ajax({
        type:"POST",
        url: ajaxUrl + '/role/findLike.do',
        data:{
            Name:searchKey
        },
       success:function (data) {
        console.log(data);
           grid.setData(data);
       },
       error:function () {
            alert("111")
       }

   })
}
function onKeyEnter(e) {
    userInquire();
}
// grid.on("select",function (e) {
//     var senderEl=e.sender;
//     var recordobj=e.record;
//     var senderElData=senderEl.getData();
//     for(var i=0;i<senderElData.length;i++){
//         if(senderElData[i].no==recordobj.no){
//             senderEl.select(senderElData[i],true);
//         }
//     }
// })
